package cn.jinzhu.consumer.controller;

import cn.jinzhu.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.net.www.http.HttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserHolleController {
    @Autowired
    DiscoveryClient discoveryClient;
    @GetMapping("/hello1")
    public String hello1() throws IOException {
        HttpURLConnection con=null;
        URL url = new URL("http://localhost:1113/hello");
         con =(HttpURLConnection) url.openConnection();
         if(con.getResponseCode() == 200){
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((con.getInputStream())));
             String si=bufferedReader.readLine();
             return si;
         }
        return "";
    }
    @GetMapping("/hello2")
    public String hello2() throws IOException {
        //一个instance就是一个discoveryClient实例
        List<ServiceInstance> list = discoveryClient.getInstances("provider");//要访问的模块服务名；需要注意查询到的列表是个集合
      //因为有可能是这个项目是个集群化部署，每个集群都是个实例。所有是list
        ServiceInstance serviceInstance = list.get(0);
        String host = serviceInstance.getHost();//IP地址
        int port = serviceInstance.getPort();//端口号
        StringBuffer sb = new StringBuffer();//拼接远程地址
        HttpURLConnection con=null;
        sb.append("http://").append(host).append(":").append(port).append("/hello");
        URL url = new URL(sb.toString());
        con =(HttpURLConnection) url.openConnection();
        if(con.getResponseCode() == 200){
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((con.getInputStream())));
            String si=bufferedReader.readLine();
            return si;
        }
        return "";
    }
    int count = 0; //线性负载均衡
    @GetMapping("/hello3")
    public String hello3() throws IOException {
        //一个instance就是一个discoveryClient实例
        List<ServiceInstance> list = discoveryClient.getInstances("provider");//要访问的模块服务名；需要注意查询到的列表是个集合
        //因为有可能是这个项目是个集群化部署，每个集群都是个实例。所有是list
        ServiceInstance serviceInstance = list.get((count ++) % list.size());//取余，只能是0和1之间
        String host = serviceInstance.getHost();//IP地址
        int port = serviceInstance.getPort();//端口号
        StringBuffer sb = new StringBuffer();//拼接远程地址
        HttpURLConnection con=null;
        sb.append("http://").append(host).append(":").append(port).append("/hello");
        URL url = new URL(sb.toString());
        con =(HttpURLConnection) url.openConnection();
        if(con.getResponseCode() == 200){
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((con.getInputStream())));
            String si=bufferedReader.readLine();
            return si;
        }
        return "";
    }

    @Autowired
    @Qualifier("restTemplate")
    RestTemplate restTemplate;
    @GetMapping("/hello4")
    public String hello4(String name) throws IOException {
        StringBuffer s = new StringBuffer();
        //这里不是localhost端口是因为，你在调用注册中心的提供者为provider时候，他里面有多个端口
        //为了实现负载均衡LoadBalanced 你直接地址改为该提供者咋注册中心的名称进行模糊查询端口
        s.append("http://").append("PROVIDER").append("/hello?").append("name=").append(URLEncoder.encode(name,"UTF-8"));
        String ss= restTemplate.getForObject(s.toString(),String.class);
        ResponseEntity r=restTemplate.getForEntity(s.toString(),String.class);//带http请求和数据
        System.out.println(r.getBody());
        System.out.println(r.getStatusCode().getReasonPhrase());//获取响应吗的ok和error
        System.out.println(r.getStatusCodeValue());
        System.out.println(r.getBody());
        return ss+"------"+r;
    }


    @GetMapping("/hello5")
    public String hello5(String name) throws IOException {
        StringBuffer s = new StringBuffer();
        //这里不是localhost端口是因为，你在调用注册中心的提供者为provider时候，他里面有多个端口
        //为了实现负载均衡LoadBalanced 你直接地址改为该提供者咋注册中心的名称进行模糊查询端口
        Map map = new HashMap();
        map.put("name",name);
        String ss= restTemplate.getForObject(s.toString(),String.class);
        ResponseEntity r=restTemplate.getForEntity("http:/PROVIDER/hello?name={name}",String.class,map);//带http请求和数据
        return ss+"------"+r;
    }


    //下面二个post传递给提供者，如果提供者没有标@RequestBody 则可以用Mapvalue liked
    @GetMapping("/hello6")
    public String hello6(){ //key value传post
        User user = new User();
        user.setId(1);
        user.setName("金柱");
        user.setPass("123456");
        StringBuffer buffer = new StringBuffer();
        buffer.append("http://").append("PROVIDER").append("/add1");
        MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
        map.add("id",1);
        map.add("name","1");
        map.add("pass","1");
        return restTemplate.postForObject(buffer.toString(),map,String.class);
    }
    @GetMapping("/hello7")
    public User hello7(){//user传
        User user = new User();
        user.setId(1);
        user.setName("金柱");
        user.setPass("123456");
        StringBuffer buffer = new StringBuffer();
        buffer.append("http://").append("PROVIDER").append("/add2");
        return restTemplate.postForObject(buffer.toString(),user,User.class);
    }

    @GetMapping("/hello8")
    public void hello8(){//user传
        User user = new User();
      MultiValueMap<String,Object> m = new LinkedMultiValueMap<>();
        m.add("name","jinzhu");
        m.add("pass","123456");
        StringBuffer buffer = new StringBuffer();
        buffer.append("http://").append("PROVIDER").append("/res");
        URI uri = restTemplate.postForLocation(buffer.toString(),m);//不需要返回值，返回的就是一个URI
        restTemplate.getForObject(uri,String.class);
    }

     @GetMapping("/hello9")
    public void hello9(){
        User user =new User();
        user.setName("..");
         StringBuffer buffer = new StringBuffer();
         buffer.append("http://").append("PROVIDER").append("/put1"); //put也是可以传json和键值，但是没有返回值
         restTemplate.put(buffer.toString(),user);
         System.out.println();
     }


    @GetMapping("/hell10")
    public void hello10(){
        StringBuffer buffer = new StringBuffer();
        buffer.append("http://").append("PROVIDER").append("/delete1/{id}"); //del可以传PathVariable和键值，但是没有返回值
        restTemplate.delete(buffer.toString(),99);

    }

}
